Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题目大意:给定一个数组,代表股票每天的价格,假设可以买卖多次,但必须每次买入之前需要卖出。问最大利润。

题目难度:Medium

/**
 * Created by gzdaijie on 16/6/11
 * 发现价格下跌,就将之前买的全部卖掉,
 * 并准备买入低价格的股票
 * min 表示准备买入的价格, max 表示准备卖出的价格
 */
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length < 2) return 0;

        int len = prices.length;
        int min = prices[0];
        int max = prices[0];
        int result = 0;

        for (int i = 1; i < len; i++) {
            if (prices[i] < prices[i - 1]) {
                result += max - min;
                max = min = prices[i];
                continue;
            }
            if (prices[i] < min) {
                min = Math.min(min, prices[i]);
            } else {
                max = Math.max(max, prices[i]);
            }
        }
        return result + max - min;

    }
}
gzdaijie            updated 2016-06-11 15:02:51

results matching ""

    No results matching ""